#!/usr/bin/python
# -*- coding: utf-8 -*
from __future__ import print_function
import sys
import platform
if sys.version_info.major is 3:
    import _thread as thread
else:
    import thread

cpu_arch = platform.architecture()
print('current cpu arch:' + str(cpu_arch))

import threading
import struct
import time


class Com232Driver():

    def __init__(self, ReadHandlerFunc):
        self.__mutex_send_recv = threading.Lock()
        self.ReadHandler = ReadHandlerFunc
        isArm = cpu_arch == 'armv7l'
        self.on_data = None
        if type(cpu_arch) is tuple:
            if cpu_arch[0] is '32bit' and cpu_arch[1] is 'ELF':
                isArm = True
        if isArm:
            import serial
            import RPi.GPIO as GPIO
            GPIO.setwarnings(False)
            # 打开串口
            # ser = serial.Serial("/dev/ttyS0", 9600)
            self.__ser = serial.Serial("/dev/ttyS0", 115200)
            GPIO.setmode(GPIO.BOARD)
        else:
            self.__ser = None

        thread.start_new_thread(self.read_s, ())

    def onValidData(self, recv):
        if type(recv) is not tuple:
            return
        data1 = recv[0]
        data = []
        for i in data1:
            data.append(i)

        if time.localtime().tm_sec == 20:
            for i in range(0, len(data)):
                print('%02x ' % ord(data[i]), end='')
            print('')

        slavID = []
        slavID.append((ord(data[0])))
        slavID.append((ord(data[1])))
        if ord(data[0]) != 0xf0 and ord(data[1]) != 0x07:
            for i in range(0, len(data)):
                print('%02x ' % ord(data[i]), end='')
            print('')
        state = []
        state.append(ord(data[2]))
        state.append(ord(data[3]))
        tag = ord(data[4])
        all = []
        for i in range(2, len(data)):
            all.append(ord(data[i]))
        if self.ReadHandler is not None:
            self.ReadHandler((slavID, state, tag, all))

    def read_s(self):
        d = []
        while True:
            self.__mutex_send_recv.acquire()
            if self.__ser is not None:
                char1 = None
                try:
                    char1 = self.__ser.read(1)
                except Exception as e:
                    print('read(1) error:' + e.message);
                if char1 is not None:
                    pass
                if ord(char1) == 0x5a:
                    recv = None
                    try:
                        recv = self.__ser.read(10)
                    except Exception as e:
                        print('read(10) error: ' + e.message)
                    if recv and len(recv) is 10:
                        for i in range(0, len(recv)):
                            pass
                        self.onValidData((recv,))
            else:
                print('self.__ser id' + str(self.__ser))
                time.sleep(1)
            self.__mutex_send_recv.release()

    def __serSend(self, d):
        d = d['content']
        print('__seerial send')
        for i in range(0,len(d)):
            print('%02x ' % d[i],end='')
        print('')
        b = struct.pack('BBBBBBBBBBB',
                        0x5A,
                        d[0],
                        d[1],
                        d[2],
                        d[3],
                        d[4],
                        d[5],
                        d[6],
                        d[7],
                        d[8],
                        d[9]
                        )
        # self.__mutex_send_recv.acquire()
        if self.__ser is not None:
            self.__ser.write(b)
            self.__ser.flushInput()
        # self.__mutex_send_recv.release()

    def send_test(self):
        try:
            newID = [0x01, 0x02]
            masterID = [0xf1, 0x07]
            d = [masterID[0], masterID[1], 0x51, 0xff, 0x6f, 0x06, newID[0], newID[1], 0x00, 0x00]
            # SerSend(d)

            masterID = newID
            deng1 = 0x1
            deng2 = 0x1
            d = [masterID[0], masterID[1], deng1, deng2, 0x6f, 0x06, newID[0], newID[1], 0x00, 0x00]
            while True:
                deng1 = deng1 << 1
                deng2 = deng2 << 1
                d = [masterID[0], masterID[1], deng1 % 255, deng2 % 255, 0x6f, 0x06, newID[0], newID[1], 0x00, 0x00]
                self.__serSend(d)
                time.sleep(1.0 / 12.0)
            exit(1)

        except KeyboardInterrupt:
            print('recv a keyboard interrupte')

    def __del__(self):
        if self.__ser is not None:
            self.__ser.close()

    def send(self, data):
        try:
            self.__serSend(data)
        except Exception as e:
            print('recv a serSend data exception:' + str(e.message))

def func(args):
    pass

def main():
    a = Com232Driver(func)
    d = [32, 00, 0xff, 0xff, 0x6f, 0x06, 00, 00, 0x00, 0x00]
    ad=dict()
    ad['content']=d
    def shif(d, n):
        d[n] = d[n] <<1
        if d[n] >= 255:
            d[n]=1

    while True:
        shif(d,3)
        shif(d,2)
        ad['content']=d
        a.send(ad)
        time.sleep(1.0 / 20)


if __name__ == '__main__':
    main()
